Implement promisify()
June 17, 2021
Promises are used in many codebases and drives the bulding blocks for synchronous methods. It allows your state to take direction in a route in which you give it. MDN represents it best in a machine state analogy:
A
Promise
is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
A Promise
is a special JavaScript object that links these states together.
My Definition of a Promise
Bring back my coffee, and please make sure it's not an iced coffee š . Isn't that Promise. On a serious note, it's a promise to return something eventually. MDN has many examples on how you can chain things together and don't have to be explicit.
How to promisfy a function?
One of the most dreaded interview questions most developers don't want to see (because it can catch you off-guard). Luckily, I had to chance to try it out on bigfrontend.dev. The idea is you'll have a function that's gonna eventually return a function, and then when you invoke that, it's gonna be a Promise, so you can chain it.
Here's my implementation:
/** * @param {(...args) => void} func * @returns {(...args) => Promise<any} */function promisify(func) { // your code here return function(...args) { return new Promise((resolve, reject) => { const cb = (error, data) => { if (error) { reject(error) } else { resolve(data) } } func.apply(this, args.concat(cb)); }) }}
const func = (arg1, arg2, cb) => {}
let promiseFn = promisify(func);
// chaining processpromiseFn().then(...).then(...)
Conclusion
A promise
gives us more flexibility and better code flow. It allows us to direct a natural state of instructions that's similar to how I like to place my door dash order. Kinda.
Resources: